/**
 * 
 */
package org.dragonfire.editor.syntax.rules;

import java.util.ArrayList;
import java.util.Arrays;

import org.dragonfire.editor.AttributeManager;
import org.eclipse.jface.text.rules.ICharacterScanner;
import org.eclipse.jface.text.rules.IRule;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.Token;
import org.eclipse.swt.SWT;

/**
 * @author Darth Android
 * @date Dec 27, 2007
 */
public class KeywordRule implements IRule {

	static {
		AttributeManager.addDefaultAttribute("KEYWORD", 128, 128, 0, SWT.BOLD);
	}
	private ArrayList<String> keywords = new ArrayList<String>();
	private String attributeName = "KEYWORD";

	public KeywordRule(ArrayList<String> keywords) {
		this.keywords = (ArrayList<String>) keywords.clone();
	}

	public KeywordRule(ArrayList<String> keywords, String attributeName) {
		this(keywords);
		this.attributeName = attributeName;
	}

	public KeywordRule(String[] keywords) {
		this(new ArrayList<String>(Arrays.asList(keywords)));
	}

	public KeywordRule(String[] keywords, String attributeName) {
		this(new ArrayList<String>(Arrays.asList(keywords)), attributeName);
	}

	public IToken evaluate(ICharacterScanner scanner) {
		ArrayList<String> matches = (ArrayList<String>) keywords.clone();
		int readchars = 0;
		String word = "";
		String wordMatch = "";
		while (matches.size() > 0) {
			int c = scanner.read();
			readchars++;
			if (c == ICharacterScanner.EOF)
				break;
			word += (char) c;
			for (int i = 0; i < matches.size(); i++) {
				String match = matches.get(i);
				if (match.length() < word.length()) {
					matches.remove(i--);
					break;
				}
				if (word.equals(match)) {
					wordMatch = match;
					if (matches.size() == 1)
						return AttributeManager.getToken(attributeName);
				}
				if (!word.equals(match.substring(0, word.length())))
					matches.remove(i--);
			}
		}
		while (readchars - wordMatch.length() > 0) {
			scanner.unread();
			readchars--;
		}
		if (!wordMatch.equals(""))
			return AttributeManager.getToken(attributeName);
		return Token.UNDEFINED;
	}
}
